package cn.jietuo.first.class02;

import java.util.Stack;

/**
 * @author zhangx & jietuo_zx@163.com
 * @version 1.0
 * @date 2020/6/18
 * @description: 使用栈结构实现队列
 */
public class Code06_TwoStackImplementQueue {

    public static class TwoStackQueue{

        private Stack<Integer> stackPush;
        private Stack<Integer> stackPop;

        public TwoStackQueue(){
            stackPush = new Stack<Integer>();
            stackPop = new Stack<Integer>();
        }

        public void add(int value){
            stackPush.push(value);
            pushToPop();
        }

        private void pushToPop() {
            if (stackPop.isEmpty()){
                while (!stackPush.isEmpty()){
                    stackPop.push(stackPush.pop());
                }
            }
        }

        public Integer poll(){
            if (stackPop.isEmpty() && stackPush.isEmpty()){
                throw new RuntimeException("queue is empty");
            }
            pushToPop();
            return stackPop.pop();
        }

        public Integer peek(){
            if (stackPop.isEmpty() && stackPush.isEmpty()){
                throw new RuntimeException("queue is empty");
            }
            pushToPop();
            return stackPop.peek();
        }
    }

    public static void main(String[] args) {
        TwoStackQueue twoStackQueue = new TwoStackQueue();
        twoStackQueue.add(10);
        twoStackQueue.add(120);
        twoStackQueue.add(130);
        twoStackQueue.add(140);
        System.out.println(twoStackQueue.peek());
        System.out.println(twoStackQueue.poll());
        twoStackQueue.add(150);
        System.out.println(twoStackQueue.peek());
        System.out.println(twoStackQueue.poll());
    }
}
